/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package serverapplication;

import pack.QuestionVoteProcess;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import pack.Command;
import static serverapplication.GlobalVariables.*;

/**
 *
 * @author shuyi
 */
public class VoteStartService implements Runnable {

    VoteStartService(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        byte command = Command.DUMMY;
        try {
            out = new ObjectOutputStream(socket.getOutputStream());
            in = new ObjectInputStream(socket.getInputStream());
            command = in.readByte();
            if (command == Command.QUESTION_START_VOTING) {
                int question_id = in.readInt();
                globalVariableLock.lock();
                try {
                    if (!questionInVoting.containsKey(question_id)) { // the question has not started yet. start it now
                        questionInVoting.put(question_id, new QuestionVoteProcess(socket, in, out));
                    } else { // the question is already in voting, there must be some error here
                    }
                } finally {
                    globalVariableLock.unlock();
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(VoteStartService.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    private Socket socket;
    private ObjectInputStream in;
    private ObjectOutputStream out;
}
